// 文档地址 https://ext.dcloud.net.cn/plugin?id=8690
// const KJFFmpeg = uni.requireNativePlugin("KJ-FFmpeg");
import request from "./request.js";
import config from "./config.js";
import util from "./util.js";
export default {
	
	// 将视频转为音频
	videoToAudio(e){
		let _this = this;
		return new Promise((resolve) => {
			_this.createTemp().then((temp) => {
				if(temp.status){
					let inPath = decodeURI("file://" + plus.io.convertLocalFileSystemURL(e.path));
					let outPath = decodeURI("file://" + plus.io.convertLocalFileSystemURL(`_doc/${config.tempPath}/${util.random_char(30)}.${e.toExt || "mp3"}`));
					KJFFmpeg.startCommand({ command: `-i "${inPath}" -vn "${outPath}"` }, (res) => {
						if (res.returnCode == 0) {
							resolve({ status: true, msg: "视频转音频成功", path: outPath });
						} else if (res.returnCode == 255) {		// 取消
							
						} else {
							resolve({ status: false, msg: "视频转音频失败" });
						}
					}, (res) => {	// 进度回调
						e.onProgress && e.onProgress(res);
					}, (res) => {	// 开始回调
						
					}, (res) => {	// LOG回调
						
					});
				}else{
					resolve({ status: false, msg: "缓存目录创建失败" });
				}
			});
		});
	},
	
	// 音频转格式
	audioToExt(e){
		let _this = this;
		return new Promise((resolve) => {
			_this.createTemp().then((temp) => {
				if(temp.status){
					let inPath = decodeURI("file://" + plus.io.convertLocalFileSystemURL(e.path));
					let outPath = decodeURI("file://" + plus.io.convertLocalFileSystemURL(`_doc/${config.tempPath}/${util.random_char(30)}.${e.toExt || "mp3"}`));
					KJFFmpeg.startCommand({ command: `-i "${inPath}"${e.otherParam ? e.otherParam : ""} -vn "${outPath}"` }, (res) => {
						if (res.returnCode == 0) {
							resolve({ status: true, msg: "音频转格式成功", path: outPath });
						} else if (res.returnCode == 255) {		// 取消
							
						} else {
							resolve({ status: false, msg: "音频转格式失败" });
						}
					}, (res) => {	// 进度回调
						e.onProgress && e.onProgress(res);
					}, (res) => {	// 开始回调
						
					}, (res) => {	// LOG回调
						
					});
				}else{
					resolve({ status: false, msg: "缓存目录创建失败" });
				}
			});
		});
	},
	
	// 音频裁剪片段  startTime开始时间如00:04   cropDuration裁剪时长如00:02 代表从00:04 - 00:06裁剪
	audioCrop(e){
		let _this = this;
		return new Promise((resolve) => {
			_this.createTemp().then((temp) => {
				if(temp.status){
					let inPath = decodeURI("file://" + plus.io.convertLocalFileSystemURL(e.path));
					let outPath = decodeURI("file://" + plus.io.convertLocalFileSystemURL(`_doc/${config.tempPath}/${util.random_char(30)}.${util.getSuffix(inPath)}`));
					KJFFmpeg.startCommand({ command: `-i ${inPath} -vn${util.getSuffix(inPath) === "flac" ? "" : " -acodec copy"} -ss ${e.startTime} -t ${e.cropDuration} ${outPath}` }, (res) => {
						if (res.returnCode == 0) {
							resolve({ status: true, msg: "音频裁剪成功", path: outPath });
						} else if (res.returnCode == 255) {		// 取消
							
						} else {
							resolve({ status: false, msg: "音频裁剪失败" });
						}
					}, (res) => {	// 进度回调
						e.onProgress && e.onProgress(res);
					}, (res) => {	// 开始回调
						
					}, (res) => {	// LOG回调
						
					});
				}else{
					resolve({ status: false, msg: "缓存目录创建失败" });
				}
			});
		});
	},
	
	// 调整语速和音量
	audioDbSpeed(e){
		let _this = this;
		return new Promise((resolve) => {
			_this.createTemp().then((temp) => {
				if(temp.status){
					let inPath = decodeURI("file://" + plus.io.convertLocalFileSystemURL(e.path));
					let outPath = decodeURI("file://" + plus.io.convertLocalFileSystemURL(`_doc/${config.tempPath}/${util.random_char(30)}.${util.getSuffix(inPath)}`));
					let originalVolume = e.originalVolume ? (e.originalVolume / 100) : 1; // 原始音频音量
					let originalSpeed = e.originalSpeed ? e.originalSpeed : 1; // 原始音频语速
					KJFFmpeg.startCommand({ command: `-i ${inPath} -filter:a "atempo=${originalSpeed},volume=${originalVolume}" ${outPath}` }, (res) => {
						if (res.returnCode == 0) {
							resolve({ status: true, msg: "音频调整成功", path: outPath });
						} else if (res.returnCode == 255) {		// 取消
							
						} else {
							resolve({ status: false, msg: "音频整失败" });
						}
					}, (res) => {	// 进度回调
						e.onProgress && e.onProgress(res);
					}, (res) => {	// 开始回调
						
					}, (res) => {	// LOG回调
						
					});
				}else{
					resolve({ status: false, msg: "缓存目录创建失败" });
				}
			});
		});
	},
	
	// 添加背景音乐
	audioPushBackground(e) {
		let _this = this;
		return new Promise((resolve) => {
			_this.createTemp().then((temp) => {
				if(temp.status){
					let bg = decodeURI("file://" + plus.io.convertLocalFileSystemURL(e.bg)); // 背景音乐地址
					let inPath = decodeURI("file://" + plus.io.convertLocalFileSystemURL(e.path)); // 原始音频地址
					let outPath = decodeURI("file://" + plus.io.convertLocalFileSystemURL(`_doc/${config.tempPath}/${util.random_char(30)}.mp3`)); // 输出后的音频地址
					let originalVolume = e.originalVolume ? (e.originalVolume / 100) : 1; // 原始音频音量
					let originalSpeed = e.originalSpeed ? e.originalSpeed : 1; // 原始音频语速
					let backgroundVolume = e.backgroundVolume ? (e.backgroundVolume / 100) : 1; // 背景音音量
					let backgroundLoop = e.backgroundLoop !== undefined ? (e.backgroundLoop ? -1 : 0) : -1; // 背景音是否循环
					KJFFmpeg.startCommand({ command: `-i ${inPath} -i ${bg} -filter_complex "[0:a]volume=${originalVolume},atempo=${originalSpeed}[a0];[1:a]aloop=loop=${backgroundLoop}:size=2e+09[a1];[a1]volume=${backgroundVolume}[a12];[a0][a12]amix=inputs=2:duration=first:dropout_transition=2" ${outPath}` }, (res) => {
						_this.getAudioInfo(outPath).then((res) => {	// 添加背景音的这个有点奇怪，返回的res为空，需要通过获取音频信息来判断，获取得到信息就视为成功
							if(res.status){
								resolve({ status: true, msg: "背景音添加成功", path: outPath });
							}else{
								resolve({ status: false, msg: "背景音添加失败" });
							}
						});
					}, (res) => {	// 进度回调
						e.onProgress && e.onProgress(res);
					}, (res) => {	// 开始回调
						
					}, (res) => {	// LOG回调
						
					});
				}else{
					resolve({ status: false, msg: "缓存目录创建失败" });
				}
			});
		});
	},
	
	// 获取音视频信息
	getAudioInfo(path){
		let _this = this;
		return new Promise((resolve) => {
			KJFFmpeg.ffprobe_getMediaInformation({ filePath: path, timeout: 60000 }, (res) => {
			    if (res.returnCode == 0 && res.allProperties && res.allProperties.format) {
					res.allProperties.format.duration = parseFloat(res.allProperties.format.duration);
					res.allProperties.format.size = parseFloat(res.allProperties.format.size);
					res.allProperties.format.bit_rate = parseFloat(res.allProperties.format.bit_rate);
					resolve({ status: true, msg: "音视频信息获取成功", info: res.allProperties.format });
			    } else {
					resolve({ status: false, msg: "音视频信息获取失败" });
			    }
			}, (res) => {
				// log回调
			});
		});
	},
	
	// 停止当前FFmpeg操作
	stopFFmpeg() {
		KJFFmpeg.cancelAll();
	},
	
	// 创建缓存目录
	createTemp(){
		let _this = this;
		return new Promise((resolve) => {
			plus.io.resolveLocalFileSystemURL("_doc/", function(entry){
				entry.getDirectory(config.tempPath, { create:true, exclusive:false }, function(dir){
					resolve({ status: true });
				}, function(){
					resolve({ status: false });
				});
			});
		});
	},
	
	// 删除缓存目录
	deleteTemp(){
		let _this = this;
		return new Promise((resolve) => {
			plus.io.resolveLocalFileSystemURL(`_doc/${config.tempPath}`, function(entry){
				entry.removeRecursively(function() {
					resolve({ status: true });
				}, function(e) {
					resolve({ status: false });
				});
			});
		});
	},

};